package thread;

public class TestDemo10 {

    public static volatile boolean flag = true;
    public static void main2(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            while (flag) {

            }
        });
        t.start();
        Thread.sleep(1000);
        // 设置标志位,让 t 线程终止
        flag = false;
        System.out.println("主线程终止");
    }

    // interrupt()标记线程是否被中断
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Thread");
                try {
                    // 这个线程绝大部分都在休眠状态
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    // 触发异常后，立即退出循环
                    break;
                }
            }
        });
        t.start();
        Thread.sleep(5000);
        // 让t线程终止 ----- 就会更改状态 ---> 就绪态-终止
        // 如果位于阻塞态(睡眠) --- 就会抛异常
        t.interrupt();
    }
}
